package com.example.lianjuan.Utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import com.example.lianjuan.Base.BaseApplication;
import com.example.lianjuan.Model.domain.CacheWithDuration;
import com.google.gson.Gson;

public class JsonCacheUtil {
    private static JsonCacheUtil mJsonCacheUtil = null;
    private String JSON_CACHE_NAME = "json_cache_name";
    private final SharedPreferences mSp;
    private Gson mGson;

    private JsonCacheUtil() {
        mSp = BaseApplication.getContext().getSharedPreferences(JSON_CACHE_NAME, Context.MODE_PRIVATE);
        mGson = new Gson();
    }

    /**
     * 保存数据
     *
     * @param key
     * @param value
     */
    public void saveCache(String key, Object value) {
        this.saveCache(key, value, -1L);
    }

    /**
     * 保存数据，多长时间有效
     *
     * @param key
     * @param value
     * @param duration
     */
    public void saveCache(String key, Object value, long duration) {
        //把内容转成json
        String valueStr = mGson.toJson(value);
        if (duration != -1L) {
            duration += System.currentTimeMillis();
        }
        //把保存的时间和内容转成对象，然后转成json
        CacheWithDuration cacheWithDuration = new CacheWithDuration(valueStr, duration);
        String cacheWithTime = mGson.toJson(cacheWithDuration);
        mSp.edit().putString(key, cacheWithTime).apply();
    }

    /**
     * 删除数据
     *
     * @param key
     */
    public void delCache(String key) {
        mSp.edit().remove(key).apply();
    }

    /**
     * 获取数据
     *
     * @param key
     */
    public <T> T getValue(String key, Class<T> clazz) {
        String valueWithDuration = mSp.getString(key, null);
        if (valueWithDuration == null) {
            return null;
        }
        LogUtils.d(this, "valueWithDuration---->" + valueWithDuration);
        CacheWithDuration cacheWithDuration = mGson.fromJson(valueWithDuration, CacheWithDuration.class);
        long duration = cacheWithDuration.getDuration();
        if (duration != -1L && duration - System.currentTimeMillis() <= 0) {
            //过期了
            return null;
        } else {
            //没过期
            LogUtils.d(this, "---->" + cacheWithDuration.getCache());
            T result = mGson.fromJson(cacheWithDuration.getCache(), clazz);
            return result;
        }
    }

    public static JsonCacheUtil getInstance() {
        if (mJsonCacheUtil == null) {
            mJsonCacheUtil = new JsonCacheUtil();
        }
        return mJsonCacheUtil;
    }
}
